﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using FDSQLAssistant.Extensions;
using FDSQLAssistant.Models;

namespace FDSQLAssistant.Busi
{
    public class FDContext
    {
        private static readonly string _configName = "config.json";

        public IServiceProvider Provider { private set; get; }

        private FDContext()
        {
            Load();
        }

        public static FDContext Default => new FDContext();

        public SysConfig SysConfig { get; private set; }

        public void Load()
        {
            var res = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), _configName));
            SysConfig = res.FomJson<SysConfig>();
            if (SysConfig == null || SysConfig.Connections == null || SysConfig.Connections.Count == 0)
                throw new Exception("请配置好连接串！");
            SysConfig.Connections.Sort(new ConfigSortComparer());
        }

        public void SetProvider(IServiceProvider provider)
        {
            Provider = provider;
        }

        private class ConfigSortComparer : IComparer<Config>
        {
            public int Compare(Config x, Config y)
            {
                if (x.Order == y.Order)
                {
                    return 0;
                }

                if (x.Order < y.Order)
                {
                    return -1;
                }

                return 1;
            }
        }
    }
}
